<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${pageType === 'add' ? '新增' : pageType === 'edit' ? '编辑' : '详情'}-自动排班规则`"
		width="860px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		:show-confirm-btn="pageType !== 'detail'"
		:show-cancel-btn="pageType !== 'detail'"
		:show-close-btn="pageType === 'detail'"
		@on-close="onVisibleChange(false)"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :hide-required-asterisk="pageType === 'detail'" label-width="110px" :show-message="false">
			<div ref="box1">
				<el-tag type="primary" class="margin-bottom-4" effect="plain">
					<span class="el-icon-tickets item-gap"></span>
					<span>基本信息</span>
				</el-tag>
				<jk-card>
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="车间" prop="workshopId">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.workshopName }}</span>
								<jk-select
									v-else
									v-model="ruleForm.workshopId"
									:option-list="workshopList"
									class="width-100-percent"
									placeholder="车间"
									size="medium"
									@change="onWorkshopChange"
								></jk-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="生效日期">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.takeEffectDate }}</span>
								<jk-date-picker
									v-else
									v-model="ruleForm.takeEffectDate"
									size="medium"
									style="width: 100%;"
									placeholder="失效日期"
								></jk-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="失效日期" prop="invalidDate">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.invalidDate }}</span>
								<jk-date-picker
									v-else
									v-model="ruleForm.invalidDate"
									size="medium"
									style="width: 100%;"
									placeholder="生效日期"
								></jk-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-0" label="单次预排班次" prop="advanceDays">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.advanceDays }}</span>
								<jk-number-input
									v-else
									v-model="ruleForm.advanceDays"
									:min="0"
									class="width-100-percent"
									placeholder="单次预排班次"
									size="medium"
								></jk-number-input>
							</el-form-item>
						</el-col>
						<!--<el-col :span="24">
							<el-form-item class="margin-bottom-10" label="备注">
								<span v-if="pageType === 'detail'" class="read-only-2">{{ ruleForm.remark }}</span>
								<jk-input v-else v-model="ruleForm.remark" type="textarea" placeholder="请输入" />
							</el-form-item>
						</el-col>-->
					</el-row>
				</jk-card>
				<div class="margin-bottom-4 margin-top-10 flex-between-center">
					<div class="flex-start-center">
						<el-tag type="primary" effect="plain">
							<span class="el-icon-tickets item-gap"></span>
							<span>班组明细</span>
						</el-tag>
					</div>
					<el-button
						v-show="pageType !== 'detail'"
						size="mini"
						circle
						type="primary"
						icon="el-icon-refresh-right"
						@click="onResetBtn"
					></el-button>
				</div>
			</div>
			<jk-table
				ref="jkTable"
				border
				:data="ruleForm.scheduleRuleDetailList || []"
				:height="dialogTableHeight - 10"
			>
				<vxe-column :visible="pageType !== 'detail'" width="60" align="center">
					<template #default>
						<div class="drag-btn"><i class="el-icon-rank"></i></div>
					</template>
					<template #header>
						<el-popover title="提示" content="双击拖动调整顺序！" placement="bottom" trigger="hover">
							<i slot="reference" class="el-icon-info drag-info-icon"></i>
						</el-popover>
					</template>
				</vxe-column>
				<vxe-column title="序号" align="center" type="seq" :width="80"></vxe-column>
				<vxe-column title="班组" align="center" field="groupName" :width="100"></vxe-column>
				<vxe-column
					:visible="pageType !== 'detail'"
					title="操作"
					align="center"
					field="operation"
					:width="160"
				>
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-delete" class="item-gap" @click="onDeleteWeekItem(scope.rowIndex)"></jk-button>
							<jk-button size="mini" icon="el-icon-arrow-up" class="item-gap" @click="onSortPlacementBtn('top', scope.rowIndex)"></jk-button>
							<jk-button size="mini" icon="el-icon-arrow-down" @click="onSortPlacementBtn('bottom', scope.rowIndex)"></jk-button>
						</div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        workforceManagementScheduleRuleCreate,
        workforceManagementScheduleRuleUpdate,
        workforceManagementScheduleRuleGet
    } from '../../../api/schedule/autoScheduleRule';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import Sortable from 'sortablejs';
    import { formatDate } from '../../../utils/jk/jk-tool';
    export default {
        components: {
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            pageType: {
                type: [String],
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                groupList: [],
                tableData: [],
                workshopList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    typeId: '',
                    typeCode: '',
                    typeName: '',
                    workshopId: '',
                    workshopCode: '',
                    workshopName: '',
                    takeEffectDate: '',
                    invalidDate: '',
                    remark: '',
                    advanceDays: 1,
                    scheduleRuleDetailList: []
                },
                rules: {
                    advanceDays: [{ required: true, trigger: 'change' }],
                    takeEffectDate: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onResetBtn() {
                this.$set(this.ruleForm, 'scheduleRuleDetailList', JSON.parse(JSON.stringify(this.groupList)));
            },
            onSortPlacementBtn(placement, rowIndex) {
                if (placement === 'top') {
                    if (rowIndex !== 0) {
                        const currRow = this.ruleForm.scheduleRuleDetailList.splice(rowIndex, 1)[0];
                        this.ruleForm.scheduleRuleDetailList.splice(rowIndex - 1, 0, currRow);
                    }
                } else {
                    if (rowIndex !== this.ruleForm.scheduleRuleDetailList.length - 1) {
                        const currRow = this.ruleForm.scheduleRuleDetailList.splice(rowIndex, 1)[0];
                        this.ruleForm.scheduleRuleDetailList.splice(rowIndex + 1, 0, currRow);
                    }
                }
            },
            onDeleteWeekItem(rowIndex) {
                this.ruleForm.scheduleRuleDetailList.splice(rowIndex, 1);
            },
            getGroupListRequest() {
                this.groupList = [];
                if (!this.ruleForm.workshopId) return;
                return personnelGroupPage({
                    auditState: 1,
                    workshopId: this.ruleForm.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res ? res.data.res.map(x => {
                            return {
                                groupId: x.id,
                                groupCode: x.code,
                                groupName: x.name
                            };
                        }) : [];
                        if (!this.dataId) {
                            this.$set(this.ruleForm, 'scheduleRuleDetailList', JSON.parse(JSON.stringify(this.groupList)));
                        }
                    }
                });
            },
            onWorkshopChange() {
                this.$set(this.ruleForm, 'scheduleRuleDetailList', []);
                this.getGroupListRequest();
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                params.scheduleRuleDetailList.forEach((x, index) => {
                    x.sortNum = index + 1;
                });
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopId = workshopItem.id;
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? workforceManagementScheduleRuleCreate : workforceManagementScheduleRuleUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return workforceManagementScheduleRuleGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res || {};
                        this.ruleForm = resData;
                        this.$nextTick(() => {
                            this.$refs.jkTable.$refs.xTable.refreshColumn();
                        });
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'takeEffectDate', formatDate(Date.now()));
                }
                if (this.dataId) await this.getDetailRequest();
                await this.getGroupListRequest();
                this.showLoading = false;
            },
            loadSortTable() {
                this.$nextTick(() => {
                    const xTable = this.$refs.jkTable.$refs.xTable;
                    this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 500,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.ruleForm.scheduleRuleDetailList.splice(oldIndex, 1)[0];
                            this.ruleForm.scheduleRuleDetailList.splice(newIndex, 0, currRow);
                        }
                    });
                });
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.loadSortTable();
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.drag-btn {
    cursor: move;
    color: #2d8cf0;
    transition: all .5s;
    font-size: 18px;
}
.drag-btn:hover {
    transform: rotate(90deg);
}
</style>
